package top.kpromise.fastdev.goods.utils;

import java.util.ArrayList;
import java.util.HashMap;

public class CommonTools {

    public static ArrayList<HashMap<String, Object>> groupMap(ArrayList<HashMap<String, Object>> arrayList,
                                                              String groupKey, String childListName) {
        ArrayList<HashMap<String, Object>> resultList = new ArrayList<>();
        String currentValue = null;
        ArrayList<HashMap<String, Object>> lastArray = new ArrayList<>();

        //  类似于 哨兵的作用，没有这个 item 最后一组 sku 将不会添加
        HashMap<String, Object> lastItem = new HashMap<>();
        lastItem.put(groupKey, "");
        arrayList.add(lastItem);

        for (HashMap<String, Object> map : arrayList) {
            String keyValue = map.get(groupKey).toString();
            if (!keyValue.equals(currentValue)) {
                if (!lastArray.isEmpty()) {
                    HashMap<String, Object> item = new HashMap<>();
                    item.put(groupKey, currentValue);
                    item.put(childListName, lastArray);
                    resultList.add(item);
                }
                lastArray = new ArrayList<>();
                currentValue = keyValue;
            }
            map.remove(groupKey);
            lastArray.add(map);
        }
        return resultList;
    }
}
